from django.shortcuts import render
from django.http import HttpResponse
from ..models import *
from django.core.urlresolvers import reverse
from django.contrib.auth.hashers import make_password, check_password
from project_1.settings import BASE_DIR
from django.contrib.auth.decorators import permission_required

# 后台用户  列表显示
@permission_required('myadmin.show_user',raise_exception=True)
def userindex(request):
	# 获取数据库数据
	data = Users.objects.all()
	# -------------------------------
	from django.core.paginator import Paginator
	from django.db.models import Q
	# 实例化分页类
	paginator = Paginator(data,5)
	# ------- 搜索-------
	sou = request.GET.dict()
	if len(sou)>1:
		stau = {"禁用":1,"正常":0}
		if sou['types'] == "all":
			res = Users.objects.filter(Q(id__contains=sou['textVal'])|Q(username__contains=sou['textVal'])|Q(phone__contains=sou['textVal'])|Q(email__contains=sou['textVal'])|Q(age__contains=sou['textVal']))
		elif sou['types'] == "status":
			st = stau[sou['textVal']]
			res = Users.objects.filter(status=st)
		else:
			if sou['types'] == "":
				res = Users.objects.filter(Q(id__contains=sou['textVal'])|Q(username__contains=sou['textVal'])|Q(phone__contains=sou['textVal'])|Q(email__contains=sou['textVal'])|Q(age__contains=sou['textVal']))
			else:
				da = {sou['types']+"__contains":sou['textVal']}
				res = Users.objects.filter(**da).exclude(status=3)
		paginator = Paginator(res,5)

	# 获取当前页码
	try:
		p = int(request.GET.get('p',1))
	except:
		p = 1

	# 获取分页数据对象[{id:1},{id:2}]  [{id:3},{id:4}]
	goodslist= paginator.page(p)

	return render(request,'myadmin/user/index.html',{"data":goodslist})
# 封装加密密码函数

def getPwd(pwd):
	upass = make_password(pwd, None, 'pbkdf2_sha256')
	pwd = check_password(upass,'pbkdf2_sha256$36000$197nqXM6yxYv$Zxh/Vsns8qszkvUmY81BgrjCeLPXhCHLEilP6VO+Rnc=')
	return upass
# 后台用户添加
@permission_required('myadmin.insert_user',raise_exception=True)
def useradd(request):
	import hashlib
	if request.method == "GET":
		return render(request,'myadmin/user/add.html')
	else:
		data = request.POST.dict()
		
		data.pop('csrfmiddlewaretoken')
		myfile = request.FILES.get('pic_url')
		# 密码加密
		
		data['password'] = getPwd(data['password'])
		try:
			if myfile != None:
				res = loadFile(myfile)
				data['pic_url'] = res
			else:
				data['pic_url'] = '/static/myadmin/img/default.jpg'
			if not data['age']:
				data['age']=None
			user = Users(**data)
			user.save()
			return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_user_index')+'"</script>')
		except:
			return HttpResponse('<script>alert("添加失败");location.href="'+reverse('myadmin_user_index')+'"</script>')
		
# 封装图片上传函数
def loadFile(myfile):
	import time
	filename = str(time.time())+"."+myfile.name.split(".").pop()
	openfile = open(BASE_DIR+'/static/myadmin/img/'+filename,"wb+")
	for i in myfile.chunks():
		openfile.write(i)
	openfile.close()
	return "/static/myadmin/img/"+filename

# 后台-会员修改
@permission_required('myadmin.update_user',raise_exception=True)
def userupdate(request,uid):
	import os
	data = Users.objects.get(id=uid)
	try:
		if request.method == 'GET':
			return render(request,'myadmin/user/update.html',{"data":data})
		else:
			da1 = request.GET.dict()
			if da1['p'] == "":
				da1['p']=1
			res = "?"
			for v,k in da1.items():
				res += v+"="+str(k)+"&"
			da = request.POST.dict()
			da.pop('csrfmiddlewaretoken')
			data.username = da['username']
			# 加密
			data.password = da['password']
			
			data.email = da['email']
			data.sex = da['sex']
			data.age = da['age']
			myfile = request.FILES.get('pic_url')
			if myfile == None:
				data.save()
			else:
				if data.pic_url != None:
					if data.pic_url != '/static/myadmin/img/default.jpg':
						try:
							os.remove(BASE_DIR+data.pic_url)
						except:
							pass
				data.pic_url = loadFile(myfile)
				data.save()
			return HttpResponse('<script>alert("修改成功");location.href="'+reverse('myadmin_user_index')+res[0:-1]+'"</script>')
	except:
		return HttpResponse('<script>alert("修改失败");location.href="'+reverse('myadmin_user_index')+res[0:-1]+'"</script>')

# 后台-删除会员
@permission_required('myadmin.del_user',raise_exception=True)
def userdel(request,uid):
	da = request.GET.dict()
	if da['p'] == "":
		da['p']=1
	res = "?"
	for v,k in da.items():
		res += v+"="+str(k)+"&"
	try:
		user = Users.objects.get(id=uid)
		if user.status == 3:
			user.status = 0
		else:
			user.status = 3
		user.save()
		return HttpResponse('<script>location.href="'+reverse('myadmin_user_index')+res[0:-1]+'"</script>')
	except:
		return HttpResponse('<script>location.href="'+reverse('myadmin_user_index')+res[0:-1]+'"</script>')